<?php

namespace App\Http\Controllers;

use App\Library\Crypt\Wechat\WxBizMsgCrypt;
use App\Models\WechatUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class WechatController extends Controller
{
    public function event(Request $request)
    {
        Log::info(json_encode($request->input()));
        $data = $request->input();
        if (isset($data['echostr'])) {
            $signature = $data["signature"];
            $timestamp = $data["timestamp"];
            $nonce = $data["nonce"];

            $token = 'lanzhan';
            $tmpArr = [$token, $timestamp, $nonce];
            sort($tmpArr, SORT_STRING);
            $tmpStr = implode($tmpArr);
            $tmpStr = sha1($tmpStr);
            if ($tmpStr == $signature) {
                return $data['echostr'];
            } else {
                return false;
            }
        } else {
            // 接收微信服务器发送的数据
            $data = file_get_contents('php://input');

            // 解析XML数据
            $xml = simplexml_load_string($data);
            // 提取消息类型
            $eventType = (string)$xml->Event;
            if ($eventType == 'subscribe') {
                WechatUser::query()->updateOrCreate([
                    'openid'      => $xml->FromUserName,
                    'merchant_id' => $xml->ToUserName,
                ], [
                    'is_subscribe' => 1,
                    'operate_time' => date('Y-m-d H:i:s'),
                ]);
            } elseif ($eventType == 'unsubscribe') {
                WechatUser::query()->updateOrCreate([
                    'openid'      => $xml->FromUserName,
                    'merchant_id' => $xml->ToUserName,
                ], [
                    'is_subscribe' => 0,
                    'operate_time' => date('Y-m-d H:i:s'),
                ]);
            }
//            file_put_contents('test.json', file_get_contents("php://input"));
        }
    }

    public function decryptMsg(array $signData, string $encryptMsg)
    {
        $res = @simplexml_load_string($encryptMsg, NULL, LIBXML_NOCDATA);
        $parseData = json_decode(json_encode($res), true);
        $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>";
        $fromXml = sprintf($format, $parseData['Encrypt']);
        $pc = new WxBizMsgCrypt($this->componentMsgToken, $this->componentEncryptkey, $this->componentAppid);
        $msg = '';
        $errCode = $pc->decryptMsg($signData['msg_signature'], $signData['timestamp'], $signData['nonce'], $fromXml, $msg);
        if ($errCode == 0) {
            $res = @simplexml_load_string($msg, NULL, LIBXML_NOCDATA);
            $data = json_decode(json_encode($res), true);
            return $data;
        } else {
            throw new \Exception('消息解密失败,errcode:' . $errCode);
        }
    }
}
